<template>
	<view class="page">
		<navbar backIconName="arrow-left" title="我的营商码" bgColor="transparent" :titleStyle="titleStyle"></navbar>

		<scroll-view class="scroll-view_H" style="height: calc(100vh);" scroll-y="true">
			<view class="top">
				<image mode="widthFix" style="width: 100%;display: block;" src="@/static/home/top-bg.jpg"></image>
				<view class="title-content">
					<text style="font-size: 32rpx;font-weight: bold;">河南省优化营商环境</text>
					<text style="font-size: 38rpx;font-weight: bold;margin-bottom: 30rpx;">入企监测平台</text>
					<view class="bt">
						<text>河南省发展和改革委员会</text>
						<text style="letter-spacing: 12rpx;">河南省司法厅</text>
					</view>
				</view>


			</view>
			<!-- 码 -->
			<view class="QrCode">
				<view style="width: 100%;margin-top: 80rpx;display: flex;justify-content: center;">

					<image mode="widthFix" show-menu-by-longpress="true"
						:style="{width: qrCodeWidth +'px',height: qrCodeWidth +'px',display: 'block'}" :src="imagesUrl">
					</image>


				</view>
				<view style="display: flex;align-items: center;margin-top: 40rpx;">
					<text style="font-size: 28rpx;color: #1169DB;">{{currentCompanyInfo.companyName || '-'}}</text>
					<image @click="toCompanyList" mode="widthFix"
						style="width: 40rpx;height: 40rpx;margin-left: 20rpx; display: block;"
						src="@/static/switch-ico.png"></image>
				</view>
				<view style="display: flex;align-items: center;margin-top: 40rpx;">
					<text @click="downLoadQrCode"
						style="font-size: 30rpx;color: #fff;background-color: #1169DB;padding: 14rpx 30rpx;border-radius: 30rpx;">下载经营主体固定场所码</text>
				</view>
			</view>
		</scroll-view>


		<QiyanQrcode ref="myQrCode" :text="qrCodeUrl" :logo="logoImage" :size="qrCodeWidth" :foreground="qrCodeColor"
			id="qrcode1" @filePathBack="filePathBack"></QiyanQrcode>

		<!-- 下载的二维码 -->
		<canvas canvas-id="myCanvas" style="width: 600px; height: 420px;"></canvas>

		<!-- loading -->
		<u-overlay :show="showLoading" :opacity="0.8">
			<view class="warp">
				<text style="font-size: 28rpx;color: #fff;">下载中...</text>
			</view>
		</u-overlay>

	</view>
</template>

<script>
	import QiyanQrcode from "@/components/qiyan-qrcode/qiyan-qrcode.vue"
	import store from '@/store'
	import config from '@/api/config'
	import {
		encrypt,
	} from '@/utils/sm4.js'
	let App = getApp();
	export default {
		components: {
			QiyanQrcode,
		},
		data() {
			return {
				logoImage: require('@/static/wx-ico.jpg'),
				showLoading: false,
				qrCodeWidth: App.globalData.screenWidth - 120,
				titleStyle: {
					color: "#ffffff",
					fontWeight: "bold",
					fontSize: "18px"
				},
				currentCompanyInfo: store.state.user.COMPANY_INFO,
				imagesUrl: "",
				qrCodeUrl: "",
				qrCodeColor: "#000000",
				canvas: null,
			};
		},
		onShow() {
			this.currentCompanyInfo = store.state.user.COMPANY_INFO
			this.$nextTick(() => {
				this.getQrCode()
			})
		},
		onLoad(options) {
			
		},
		methods: {
			getQrCode() {
				/* 企业信用代码sm4加密 */
				let socialNumber = encrypt(this.currentCompanyInfo.socialCreditNumber)
				/* 企业码生成链接 */
				this.qrCodeUrl = config.qrCodeRule + socialNumber
				this.$refs.myQrCode.draw()
			},
			/* 跳转已认证企业列表 */
			toCompanyList() {
				uni.navigateTo({
					url: '/pages-mine/pages/myAuthentication/index?whereFrom=myQrCode'
				});
			},
			/* 下载场所码 */
			downLoadQrCode() {
				this.getAuthorize()
			},
			/* 授权 */
			getAuthorize() {
				const that = this
				uni.getSetting({
					success: function(res) {
						if (res.authSetting['scope.writePhotosAlbum']) { // 用户授权相册权限
							that.getImageInfo()
						} else { // 用户没有授权相册权限
							uni.showModal({
								title: '提示',
								content: '用户未授权相册权限，点击授权',
								success: function(res) {
									if (res.confirm) {
										uni.authorize({
											scope: 'scope.writePhotosAlbum',
											success: () => {
												that.getImageInfo()
											},
											fail: () => { // 用户拒绝授权，引导手动开启
												uni.showModal({
													title: '提示',
													content: '需授权相册权限才能保存图片',
													success: (res) => {
														if (res.confirm)
															uni
															.openSetting();
													}
												});
											},
										})
									} else {
										uni.showToast({
											title: "用户取消授权，不能使用下载功能",
											icon: "error",
										})
									}
								},
							})
						}
					},
					fail: function(error) {

					}
				})
			},
			/* 二维码链接 */
			filePathBack(res) {
				this.imagesUrl = res
				this.init()
			},
			init() {
				const canvas = uni.createCanvasContext('myCanvas');
				this.canvas = canvas
			},
			chunkArrayInGroups(arr, size) {
				let result = []
				if (arr.length <= size) {
					return [arr]
				}
				return [arr.slice(0, size)].concat(this.chunkArrayInGroups(arr.slice(size), size))
			},
			/* 绘制企业名称 */
			drawCompanyName() {
				let name = this.currentCompanyInfo.companyName || ''
				// let name = '濮阳市建材市场龙起大建装饰材料门市'
				let maxWith = 260
				let startLeft = 310
				let startTop = 230
				let lineHeight = 38
				let nameList = name.split('')
				this.canvas.beginPath()
				this.canvas.fillStyle = '#fff'
				this.canvas.font = '26px YaHei'
				/* 字体分组 */
				let arrays = this.chunkArrayInGroups(nameList, 10)
				if (arrays.length == 1) {
					startTop = 230
				}
				if (arrays.length == 2) {
					startTop = 230
				}
				if (arrays.length == 3) {
					startTop = 212
				}
				for (let i = 0; i < arrays.length; i++) {
					let str = arrays[i].join('')
					if (i == arrays.length - 1) {
						let allWidth = this.canvas.measureText(str).width
						let startFloat = parseInt((maxWith - allWidth) / 2)
						this.canvas.fillText(str, (startLeft + startFloat),
							(startTop + i * lineHeight), maxWith)

					} else {
						this.canvas.fillText(str, startLeft,
							(startTop + i * lineHeight), maxWith)
					}
				}
			},
			getImageInfo() {
				this.showLoading = true
				if (this.canvas == null) {
					const canvas = uni.createCanvasContext('myCanvas');
					this.canvas = canvas
				}
				let bgUrl = require('@/pages-mall/static/qrcode-bg.png')
				this.canvas.drawImage(bgUrl, 0, 0, 600,
					420)
				this.canvas.drawImage(this.imagesUrl, 56, 130, 225,
					225)
				this.drawCompanyName()
				this.canvas.draw();
				setTimeout(() => {
					this.saveImage()
				}, 1000)

			},
			saveImage: function() {
				let that = this;
				uni.canvasToTempFilePath({
					canvasId: 'myCanvas',
					fileType: 'png',
					quality: 1,
					success: function(res) {
						that.showLoading = false
						let tempFilePath = res.tempFilePath;
						uni.saveImageToPhotosAlbum({
							filePath: tempFilePath,
							success: function(res3) {
								uni.showModal({
									title: '提示',
									content: '保存到相册成功',
									confirmText: '确定',
									showCancel: false,
									confirmColor: '#1169DB',
									success(res4) {

									}
								})
							},
						});
					},
					fail: function(res) {
						that.showLoading = false
						uni.$u.toast('下载失败')
					}
				}, that);
			},
		}
	};
</script>

<style lang="scss" scoped>
	.page {
		height: calc(100vh);
		overflow: hidden;
	}

	.list {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		padding: 0 30rpx;
	}

	.warp {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100%;
	}

	.dial-nav {
		padding: 24rpx 30rpx 30rpx 30rpx;
	}

	.scroll-view_H {
		width: 100%;
		height: 100%;

		.QrCode {
			width: 100%;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
		}

		.top {
			width: 100%;
			display: flex;
			position: relative;
			color: #fff;

			.title-content {
				width: 100%;
				display: flex;
				align-items: center;
				flex-direction: column;
				position: absolute;
				bottom: 40rpx;
				text-align: center;

				.bt {
					width: 420rpx;
					padding: 10rpx 0rpx;
					display: flex;
					flex-direction: column;
					font-size: 24rpx;
					background-color: #05306D;
					opacity: .6;
					border-radius: 50rpx;
				}


			}

		}


	}
</style>